import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../data/dio/api/bt_dio_network.dart';
import '../../../data/dio/api/bt_net_data_source.dart';
import '../../../data/models/bt_broadcaster.dart';
import '../../utils/bt_constants.dart';

class BtHomeRepository {
  final logger = Logger();
  final BtNetDataSource network = BtDioNetwork();

  void fetchBroadcasterList(int page, int limit, Function(List<BtBroadcaster> btBroadcasterList) onResult) {
    var map = <String, dynamic>{};
    map['category'] = 'Popular';
    map['isPageMode'] = true;
    map['isRemoteImageUrl'] = true;
    map['limit'] = limit;
    map['page'] = page;
    map['tag'] = 'All';
    network.fetchBroadcasterList(map).then((btBroadcasterResult) {
      if (btBroadcasterResult.isSuccess) {
        onResult(btBroadcasterResult.data ?? []);
      }
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }

  Future<void> getRongCloudToken(Function(String) onResult) async {
    var map = <String, dynamic>{};
    network.getRongCloudToken(map).then((result) {
      if (result.isSuccess) {
        onResult(result.data?.value ?? '');
      }
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }

  Future<void> getStrategy() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var map = <String, dynamic>{};
    network.getStrategy(map).then((result) {
      if (result.isSuccess) {
        prefs.setString(userServiceAccountId, result.data?.userServiceAccountId ?? '');
      }
    }).catchError((error) {
      // non-200 error goes here.
      switch (error.runtimeType) {
        case DioException:
          // Here's the sample to get the failed response error code and message
          final res = (error as DioException).response;
          logger.e('Got error : ${res?.statusCode} -> ${res?.statusMessage}');
          break;
        default:
          logger.e('Error occurred: $error');
          break;
      }
    });
  }
}
